const cluster = require('cluster');

const utils = {

  /**
   * 得到client配置
   *
   * @example  getClientConfig(db1) 则会将default和db1合并的配置结果
   *
   * 配置结构如下：
   *
   * config = {
   *      clients: {
   *          db1: {},
   *          db2: {}
   *      }
   *      default: {
   *        .....
   *      }
   * }
   * @param {String} clientName - 键值
   * @return {String} 配置结果
   * @api public
   */
  getClientConfig(config, clientName) {
    if (!config.clients) {
      return undefined;
    }

    let defaultConfig = config.default || {};
    let client = config.clients[clientName];
    if (!client) {
      return Object.assign({
        database: clientName
      }, defaultConfig);

    }

    // merge default config with client
    return Object.assign({}, defaultConfig, client);
  },

  /**
   * 判断进程是否在Master上
   *@api public
   *@return {Boolean} isMaster
   */
  isMasterProcess() {

    // console.debug('process.env', process.env);
    if (process.env && process.env.pm_id) {
      //in pm2
      console.debug(`process.env.pm_id: ${process.env.pm_id}, process.env.NODE_APP_INSTANCE: ${process.env.NODE_APP_INSTANCE}`);

      if (process.env.NODE_APP_INSTANCE === '0') {
        console.debug(`master pm2 process, id is: ${process.pid}`);
        return true;
      }
      return false;
    }
    return cluster.isMaster;
  },

  /**
   * 判断进程是否在pm_id上
   *@api public
   *@param {String} pmId pm2进程编号 0,1,2,3,4,5 [CPU有几核则有多少]
   *@return {Boolean} isOnProcess
   */
  isOnProcess(pmId) {

    // console.debug('process.env', process.env);
    if (process.env && process.env.pm_id) {
      //in pm2
      console.debug(`process.env.pm_id: ${process.env.pm_id}, process.env.NODE_APP_INSTANCE: ${process.env.NODE_APP_INSTANCE}`);

      if (process.env.NODE_APP_INSTANCE === pmId) {
        console.debug(`master pm2 process, id is: ${process.pid}`);
        return true;
      }
      return false;
    }
  }
};

module.exports = utils;
